<?php
namespace wechat;
use app\common\model\Data;

use app\admin\model\UserModel;

use think\Db;
require EXTEND_PATH . 'wechat/REST.php';

class wechatCallbackapiTest
{
    /* public $appid = "wx703acc3701dcc383";
     public $secret = '1c9157d07bcb15c437b5986b7b52eba4';*/
    public $appid = "wxc7f82feeff1f94fb";
    public $secret = '94abecfdad50a8609827c1c27adba840';

    public function valid()
    {

        $echoStr = $_GET["echostr"];

        //valid signature , option
        if ($this->checkSignature()) {
            ob_clean();
            echo $echoStr;
            exit;
        }
    }

    public function rr()
    {
        $this->sendTemplateSMS('gh_636abb5249cd', 'oUVWfv3OPlBkzbRORQSCsGsBz4Lg', '生日快乐');
    }

    public function sendTextMsg($fromUsername, $toUsername, $contentStr)
    {
        $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml>";
        $time = time();
        echo sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
    }

    //自动回复功能
    public function responseMsg()
    {
        //get post data, May be due to the different environments
        //获取POST数据，可能是由于不同的环境
        //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postStr = file_get_contents("php://input");
        //extract post data
        //提取后的数据
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $msgType = $postObj->MsgType;
            $event = $postObj->Event;
	
            if ($event == 'subscribe') {
               $user = $this->user_data($fromUsername);
                $contentStr = '欢迎关注优家舒适圈！！';
                $this->sendTextMsg($fromUsername, $toUsername, $contentStr);
            }elseif($event == 'unsubscribe'){
                $this->unsubscribe($fromUsername);
            }elseif($msgType == "text"){
				 $keyword = trim($postObj->Content);
				if(trim($keyword) == '签到'){
                    //$contentStr = '2018年第二季度营销大会签到 请点击：http://cdmeijing.mikecrm.com/krjAonF';
                    $contentStr = '活动签到，请点击  http://cdmeijing.mikecrm.com/a49jqv1';
					$this->sendTextMsg($fromUsername, $toUsername, $contentStr);
				}elseif($keyword == '摇一摇'){
                    $contentStr = '微信互动游戏，请点击 http://www.hixianchang.com/pro/mobile/index.html?/#/transferRoute.html?mobileFlag=EmdliwBu&route=shake';
					$this->sendTextMsg($fromUsername, $toUsername, $contentStr);
                }elseif($keyword == '泰达'){
                    $contentStr = '活动签到请点击：http://cdmeijing.mikecrm.com/cU1EBp7';
					$this->sendTextMsg($fromUsername, $toUsername, $contentStr);
                }else{
					$re = $this->user_data($fromUsername);
					$contentStr = '欢迎关注优家舒适圈！！';
					$this->sendTextMsg($fromUsername, $toUsername, $contentStr);
				}
              
            }
        } else {
            echo "";
            exit;
        }


    }
	
	
	
    //记录关注用户
    public function user_data($openid){
		
        //获取用户信息
        $user = $this->user($openid);
		
		
        if($user['sex'] == 1){
            $sex = 1;
        }elseif($user['sex'] == 2){
            $sex = 0;
        }else{
            $sex = null;
        }

        $data =[
            'nick_name'=>$user['nickname'],
            'subscribe'=>$user['subscribe'],
            'headimgurl'=>$user['headimgurl'],
            'openid'=>$user['openid'],
            'user_sex'=>$sex,
            'subscribe_time'=>$user['subscribe_time'],
        
        ];
        //查询该微信号是否存在
        $re = Db::table('dx_user')->where('openid',$user['openid'])->count();	
        if($re){
            Db::table('dx_user')->where('openid',$user['openid'])->update($data);
        }else{
			$data['time'] = time();
			Db::table('dx_user')->insert($data);
        }
        return $re;
    }
    //取消关注
    public function unsubscribe($openid){
        $re = Db::table('dx_user')->where('openid',$openid)->count();
        if($re){
            $user = $this->user($openid);
            if($user['sex'] == 1){
                $sex = 1;
            }elseif($user['sex'] == 2){
                $sex = 0;
            }else{
                $sex = null;
            }
            $data =[
              // 'nick_name'=>$user['nickname'],
                'subscribe'=>$user['subscribe'],
                'headimgurl'=>$user['headimgurl'],
                'openid'=>$user['openid'],
                'user_sex'=>$sex,
                'subscribe_time'=>$user['subscribe_time'],
                //'time'=>time()
            ];
            Db::table('dx_user')->where('openid',$openid)->update($data);
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = "youjia";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    //获取access_token
    public function get_token()
    {
        $appid = $this->appid;
        $secret = $this->secret;
        $get_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $date = file_get_contents($get_url);
        $date = json_decode($date, true);
        return $date['access_token'];
    }

    //获取用户的基本信息
    public function user($openid)
    {
        $access_token = $this->get_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $re = file_get_contents($url);	
		
        $re = json_decode($re, true);
        return $re;
    }

    //通过code获取openid
    public function get_openid($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->secret . "&code=" . $code . "&grant_type=authorization_code";
        $re = file_get_contents($url);
        $re = json_decode($re, true);
        return $re;
    }

    //短信验证
    public function sendTemplateSMS($to, $datas, $tempId)
    {

        //主帐号,对应开官网发者主账号下的 ACCOUNT SID
        $accountSid = 'aaf98f89486445e601487dcf498108ad';

        //主帐号令牌,对应官网开发者主账号下的 AUTH TOKEN
        $accountToken = 'ccaa16808d704145bb20c418bf9c7377';

        //应用Id，在官网应用列表中点击应用，对应应用详情中的APP ID
        //在开发调试的时候，可以使用官网自动为您分配的测试Demo的APP ID
        $appId = '8aaf07085d106c7f015d4027e1c2147c';

        //请求地址
        //沙盒环境（用于应用开发调试）：sandboxapp.cloopen.com
        //生产环境（用户应用上线使用）：app.cloopen.com
        $serverIP = 'app.cloopen.com';


        //请求端口，生产环境和沙盒环境一致
        $serverPort = '8883';

        //REST版本号，在官网文档REST介绍中获得。
        $softVersion = '2013-12-26';
        // 初始化REST SDK
        //global $accountSid,$accountToken,$appId,$serverIP,$serverPort,$softVersion;

        $rest = new \REST($serverIP, $serverPort, $softVersion);

        $rest->setAccount($accountSid, $accountToken);

        $rest->setAppId($appId);


        // 发送模板短信
        echo "Sending TemplateSMS to $to <br/>";
        $result = $rest->sendTemplateSMS($to, $datas, $tempId);

        if ($result == NULL) {
            return "result error!";

        }
        if ($result->statusCode != 0) {
            return "error code :" . $result->statusCode . "<br>" . "error msg :" . $result->statusMsg;

            //echo "error code :" . $result->statusCode . "<br>";
            //echo "error msg :" . $result->statusMsg . "<br>";
            //TODO 添加错误处理逻辑
        } else {
            return "请输入验证码V+验证码(如：验证码为1234则输入V1234)";
            // 获取返回信息
            // $smsmessage = $result->TemplateSMS;
            //echo "dateCreated:".$smsmessage->dateCreated."<br/>";
            //echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
            //TODO 添加成功处理逻辑
        }
    }

    //生成随机验证码
    public function createCode($charset, $codelen)
    {
        $_len = strlen($charset) - 1;
        $code = '';
        for ($i = 0; $i < $codelen; $i++) {
            $code .= $charset[mt_rand(0, $_len)];
        }
        return $code;
    }

    //获取用户信息
    public function get_user($openid, $access_token)
    {


        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN ";
        $re = file_get_contents($url);

        $re = json_decode($re, true);
        return $re;

    }


    public function curl_wechat($url, $data)
    {

        //初始化
        $ch = curl_init();
        //设置请求地址
        curl_setopt($ch, CURLOPT_URL, $url);
        //捕获内容但不输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //模拟post发送
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        //执行
        $re = curl_exec($ch);
        //判断是否发送成功
        if ($re == false) {
            echo curl_error($ch);
        } else {
            return $re;
        }
        //关闭
        curl_close($ch);
    }

    //模板消息回复
    public function tpl_send($data)
    {
        $access_token = $this->get_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
        return $this->curl_wechat($url, $data);
    }
    //客服接口-发消息

    public function send_msg($text,$openid){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$this->get_token();
        $data = '{
                    "touser":"'.$openid.'",
                    "msgtype":"text",
                    "text":
                    {
                         "content":"'.$text.'"
                    }
                }';
        $this->curl_wechat($url,$data);
    }

    /*
     * 拉取用户
     *
     * */
    public function getuser_all(){
		set_time_limit(0);
        $access_token = $this->get_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$access_token}&next_openid";
        $re = file_get_contents($url);
        $re = json_decode($re,true);
        if($re['data']['openid']){
            foreach($re['data']['openid'] as $k=>$v){
                //查询用户资料
				$re = $this->user_data($v);
                var_dump($re);

            }
        }
    }

}